package com.scheduled;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.controller.TestController;
import com.google.common.collect.Lists;
import com.mapper.entity.StockHandle;
import com.mapper.entity.mapper.StockCirculationDetailMapper;
import com.mapper.entity.mapper.StockCirculationMapper;
import com.mapper.entity.mapper.StockHandleMapper;
import com.service.impl.HandleStockOrg;
import com.task.InsertStockAndDetailTask;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.weekend.Weekend;

import javax.sql.DataSource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: create by God of SJF
 * @version: v1.0
 * @description: com.scheduled
 * @date:2021/9/22
 */

@Component
public class StockHandleScheduled {


    @Autowired
    StockHandleMapper stockHandleMapper;

    @Autowired
    DataSource dataSource;

    @Autowired
    StockCirculationDetailMapper stockCirculationDetailMapper;

    @Autowired
    StockCirculationMapper stockCirculationMapper;

    @Autowired
    HandleStockOrg handleStockOrg;

    public static String PATH_STOCK = "/Users/libin/Desktop/分类2-切割/";

    File file2 = new File("/Users/libin/Desktop/分类3/错误");

    File file23 = new File("/Users/libin/Desktop/分类3/运行");

    static final int nThreads = Runtime.getRuntime().availableProcessors();

    public Integer poolSize = nThreads /2;

    public ThreadPoolExecutor pool = new ThreadPoolExecutor(poolSize, poolSize,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());

    @Autowired
    RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void handle() throws Exception {
        Integer  poolSizeRedis = Integer.valueOf( (String) redisTemplate.opsForValue().get("pool"));
        this.pool.setCorePoolSize(poolSizeRedis);
        this.pool.setMaximumPoolSize(poolSizeRedis);
        List<String> run = new ArrayList<>();
        run.add("pool active ==" + this.pool.getActiveCount()+"\r\n");
        run.add("pool queueSize ==" + this.pool.getQueue().size()+"\r\n");
        System.out.println("pool active ==" + this.pool.getActiveCount()+"\r\n");
        System.out.println("pool queueSize ==" + this.pool.getQueue().size()+"\r\n");
        TestController.writeFile(file23.getAbsolutePath(),run);
        if (this.pool.getQueue().size() < 20) {
            Weekend<StockHandle> weekend = Weekend.of(StockHandle.class);
            weekend.createCriteria().andEqualTo("status", 0);
            weekend.orderBy("fileName").asc();
            List<StockHandle> handles = stockHandleMapper.selectByExampleAndRowBounds(weekend,new RowBounds(0,1));
            StockHandle handle =null;
            if(!CollectionUtils.isEmpty(handles)){
                handle = handles.get(0);
            }
            if (null != handle) {
                System.out.println(handle.getFileName());
                handle.setStatus(1);
                stockHandleMapper.updateByPrimaryKey(handle);
                String name = handle.getFileName();
                File file = new File(PATH_STOCK + name);
                List<String> allList = new ArrayList<>();
                Scanner scanner = new Scanner(file);
                while (scanner.hasNextLine()) {
                    String string = scanner.nextLine();
                    JSONObject json = JSONUtil.parseObj(string);
                    allList.add(string);
                }
                List<List<String>> splits = null;
                splits = Lists.partition(allList, 2000);
                for (List<String> list : splits
                ) {
                    InsertStockAndDetailTask task = new InsertStockAndDetailTask();
                    task.setStockCirculationDetailMapper(stockCirculationDetailMapper);
                    task.setHandleStockOrg(handleStockOrg);
                    task.setList(list);
                    task.setErrorFile(file2);
                    task.setStockCirculationMapper(stockCirculationMapper);
                    this.pool.execute(task);
                }
            }
        }
    }
}